package com.zbec.mdrs.license;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zbec.mdrs.entity.license.License;
import com.zbec.mdrs.license.parser.LicenseParser;
import com.zbec.mdrs.repository.jpa.LicenseDao;
import com.zbec.mdrs.util.DateUtils;

@Service
public class LicenseCheckUtil {
	private static Logger logger = LoggerFactory.getLogger(LicenseCheckUtil.class);
	
	@Autowired
	private LicenseParser licenseParser;
	
	@Autowired
	private LicenseDao licenseDao;
	
	public String checkLicense() {
		com.zbec.mdrs.license.parser.License license;
		try {
			List<License> licList = (List<License>)licenseDao.findAllOrderByIdDesc();
			if(licList == null || licList.size() < 1){
				logger.info("Hasn't any license in the table t_license.");
				return "Y";
			}
			License lic = licList.get(0);
			if(lic == null 
					|| lic.getLicenseText() == null 
					|| StringUtils.isBlank(StringUtils.trim(lic.getLicenseText()))){
				logger.info("The latest license is null or blank in the table t_license.");
				return "Y";
			}
			license = licenseParser.getLicense(StringUtils.trim(lic.getLicenseText()));
			if(license == null || license.getStartDate() == null || license.getExpireInDays() == null){
				logger.info("Can't parser the license from the encode string.");
				return "Y";
			}
			logger.info("After parser the license ="+ToStringBuilder.reflectionToString(license));
			Date expireDate = DateUtils.addDaysToDate(
					DateUtils.toDate(license.getStartDate(), "yyyyMMdd"),
					Integer.parseInt(license.getExpireInDays()));
			if (DateUtils.compareDates(expireDate, new Date()) < 0) {
				return "Y";
			}
		} catch (Exception e) {
			return "Y";
		}

		return "N";
	}
}
